package com.lll.simple.rpc.protocol.handler;

import com.lll.simple.rpc.common.*;
import com.lll.simple.rpc.protocol.MsgType;
import com.lll.simple.rpc.protocol.ProtocolConstants;
import com.lll.simple.rpc.protocol.serialization.SerializationTypeEnum;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.TimeUnit;

/**
 * @Author: liull
 * @Description:
 * @Date: Created in 15:48 2021/2/7
 * @Modified By:
 */
public class RpcHeartBeatHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        doHeartBeat(ctx);
    }

    private void doHeartBeat(ChannelHandlerContext ctx) {
        ctx.executor().schedule(() -> {
            if (ctx.channel().isActive()) {
                RpcProtocol<RpcHeartBeat> heartBeatData = buildHeartBeatData();
                ctx.writeAndFlush(heartBeatData);
                // doHeartBeat(ctx);
            }
        }, 10, TimeUnit.SECONDS);
    }

    private RpcProtocol<RpcHeartBeat> buildHeartBeatData() {
        RpcProtocol<RpcHeartBeat> protocol = new RpcProtocol<>();
        RpcHeartBeat body = new RpcHeartBeat();
        body.setStatus((byte) 1);
        protocol.setBody(body);

        // 1.1协议header
        MessageHeader header = new MessageHeader();
        long requestId = RpcRequestHolder.REQUEST_ID.incrementAndGet();
        header.setRequestId(requestId);
        header.setMagic(ProtocolConstants.MAGIC);
        header.setSerialization((byte) SerializationTypeEnum.HESSIAN.getType());
        header.setVersion(ProtocolConstants.VERSION);
        header.setMsgType((byte) MsgType.HEARTBEAT.getType());
        header.setStatus((byte) 0x1);
        protocol.setHeader(header);
        // 1.2协议body
        protocol.setBody(body);
        return protocol;
    }

}
